using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;

public class ArrangementOperation : MonoBehaviour
{
	public GameObject itemParent;
	public GameObject partnerParent;
	public UISprite headPicSprite;
	public UILabel nameLabel;
	public UILabel levelLabel;
	public UILabel professionLabel;
	public UILabel skillLabel;
	public UILabel skillDescriptionLabel;
	public UILabel partnerCountLabel;
	public UILabel inusePartnerLabel;
	public Transform orderParent;
	public Dictionary<int,BackpackItem> partnerPosDic = new Dictionary<int, BackpackItem> ();
	public Dictionary<int,BackpackItem> partnerDic = new Dictionary<int, BackpackItem> ();
	Dictionary<int,ArrayList> partnerInfoDic = new Dictionary<int, ArrayList> ();
	Dictionary<int,ArrayList> campInfoDic = new Dictionary<int, ArrayList> ();
	Dictionary<int,Transform> orderTransformDic = new Dictionary<int, Transform> ();
	BackpackItem targetItem;
	int inUsePartnerCount = 0;
	string spriteNamePre = "deployment_number_";
	int bingPartnerIndex = -1;
	int bingCampIndex = -1;
	UIAtlas headPicAtlas;
	UIAtlas greyHeadPicAtals;
	int currentArragement;
	bool isOrderVisible = false;
	
	void Awake ()
	{
		headPicAtlas = Resources.Load (ResPath.HEADPICATLASPATH + "HeadPic", typeof(UIAtlas)) as UIAtlas;
		greyHeadPicAtals = Resources.Load (ResPath.HEADPICATLASPATH + "HeadPic_grey", typeof(UIAtlas)) as UIAtlas;
		
		BackpackItem[] items = itemParent.GetComponentsInChildren<BackpackItem> ();
		
		for (int i = 0; i < items.Length; i++) {
			string parentName = items [i].transform.parent.name;
			int tIndex = int.Parse (parentName.Substring (parentName.Length - 1));
			
			items [i].index = tIndex;
			
			partnerPosDic.Add (tIndex, items [i]);
		}
		
		BackpackItem[] partnerItems = partnerParent.GetComponentsInChildren<BackpackItem> ();
		
		for (int i = 0; i < partnerItems.Length; i++) {
			string mName = partnerItems [i].transform.name;
			int tIndex = int.Parse (mName.Substring (mName.Length - 1));
			
			partnerItems [i].index = tIndex;
			
			partnerDic.Add (tIndex, partnerItems [i]);
		}
		
		Transform[] trans = orderParent.GetComponentsInChildren<Transform> ();
		
		for (int i = 0; i < trans.Length; i++) {
			if (trans [i].parent == orderParent) {
				string mName = trans [i].name;
				int tIndex = int.Parse (mName.Substring (mName.Length - 1));
				orderTransformDic.Add (tIndex, trans [i]);
			}
		}
		
		//bingPartnerIndex = BindManage.getInstance ().BindRecord (ModelLocator.getInstance ().scene.Role, "Partner", this, "BingPartner", "RemovePartner");
		
		bingCampIndex = BindManage.getInstance ().BindRecord (ModelLocator.getInstance ().scene.Role, "Camp", this, "BingCamp", "RemoveCamp");
		
		
		MySocket.getInstance ().addEventListener ((int)SystemMsgFlag.NetMessageSC.NM_SC_CAMP_OPEN_ACK, InitMessage);
		MySocket.getInstance ().addEventListener ((int)SystemMsgFlag.NetMessageSC.NM_SC_CAMP_EXCHANGE_ACK, ExchangeArrangement);
		MySocket.getInstance ().addEventListener ((int)SystemMsgFlag.NetMessageSC.NM_SC_CAMP_ADD_PARTER_ACK, ExchangeArrangement);
		MySocket.getInstance ().addEventListener ((int)SystemMsgFlag.NetMessageSC.NM_SC_CAMP_DEL_PARTER_ACK, ExchangeArrangement);
		MySocket.getInstance ().addEventListener ((int)SystemMsgFlag.NetMessageSC.NM_SC_CAMP_SWITCH_ACK, ShowArrangement);
		
		SendInitMessageTOServer ();
		
		GetPartnerInfo ();
	}
	
	void SendInitMessageTOServer ()
	{
		ByteArrayEx byteArray = new ByteArrayEx ();
		byteArray.writeInt ((int)SystemMsgFlag.NetMessageCS.NM_CS_CAMP_OPEN_SYN);
		MySocket.getInstance ().Async_Send (byteArray.byteArray);
	}
	
	void InitMessage (System.Object getter, DispatchEventArgs e)
	{
		ByteArrayEx byteArray = new ByteArrayEx (e.data [0] as byte[]);

		Init (-1);
	}
	
	void Init (int index)
	{
		UIManagement.Instance ().SetVisiable (gameObject, GameDefine.VISIABLE);
		
		if (index < 0) {
			//头像//
			headPicSprite.spriteName = ModelLocator.getInstance ().scene.Role.GetProperties ("HeadPic").ToString ();
			//姓名//
			nameLabel.text = ModelLocator.getInstance ().scene.Role.GetProperties ("RoleName").ToString ();
			//等级//
			string strLv = BinaryReaderTool.getInstance ().getSwfLangStr ("String_LV");
			levelLabel.text = strLv + ModelLocator.getInstance ().scene.Role.GetProperties ("Level").ToString ();
			
			//职业//
			string jobName = ModelLocator.getInstance ().scene.Role.GetProperties ("JobName").ToString ();
			professionLabel.text = BinaryReaderTool.getInstance ().getSwfLangStr (jobName);
			
			//绝招//
			string skillId = ModelLocator.getInstance ().scene.Role.GetProperties ("SkillID").ToString ();
			string[] skillInfo = SqliteReader.getInstance ().getIniVal ("Skill", "SkillID", skillId, new string[]{"Name","EffectDes"});
			string skillName = skillInfo [0];
			skillLabel.text = BinaryReaderTool.getInstance ().getSwfLangStr (skillName);
			
			//绝招描述//
			string skillDescription = skillInfo [1];
			skillDescriptionLabel.text = BinaryReaderTool.getInstance ().getSwfLangStr (skillDescription);
			
			
			ShowArrangement (-1);
			
		} else {
			ulong objectId = ulong.Parse ((partnerInfoDic [index] [0].ToString ()));
			Point pos1 = new Point (0, 0, objectId);
			string[] infos = SqliteReader.getInstance ().getIniVal ("Partner", "PartnerID", pos1.QuerySrvId ().ToString (), false, new string[]{"PartnerName","Level","Type","SkillID","HeadIcon"});
			
			//头像//
			headPicSprite.spriteName = infos [4];
			//姓名//
			string partnerName = infos [0];
			nameLabel.text = BinaryReaderTool.getInstance ().getSwfLangStr (partnerName);
			//等级//
			string strLv = BinaryReaderTool.getInstance ().getSwfLangStr ("String_LV");
			levelLabel.text = strLv + infos [1];
			
			//职业//
			string roleId = infos [2];
			professionLabel.text = BinaryReaderTool.getInstance ().getSwfLangStr ("Role" + roleId);
			
			//绝招//
			string skillId = infos [3];
			string[] skillInfo = SqliteReader.getInstance ().getIniVal ("Skill", "SkillID", skillId, new string[]{"Name","EffectDes"});
			string skillName = skillInfo [0];
			skillLabel.text = BinaryReaderTool.getInstance ().getSwfLangStr (skillName);
			
			//绝招描述//
			string skillDescription = skillInfo [1];
			skillDescriptionLabel.text = BinaryReaderTool.getInstance ().getSwfLangStr (skillDescription);
		}
	}
	
	void ShowArrangementRequest (int index)
	{
		currentArragement = index;
		
		ByteArrayEx byteArray = new ByteArrayEx ();
		byteArray.writeInt ((int)SystemMsgFlag.NetMessageCS.NM_CS_CAMP_SWITCH_SYN);
		byteArray.writeByte ((byte)index);
		MySocket.getInstance ().Async_Send (byteArray.byteArray);
	}
	
	void ShowArrangement (System.Object getter, DispatchEventArgs e)
	{
		ShowArrangement (currentArragement);
	}
	
	void ShowArrangement (int index)
	{
		ulong tPoint_0 = (ulong)0;
		inUsePartnerCount = 0;
		
		for (int i = 0; i < partnerInfoDic.Count; i++) {
			ulong objectId = ulong.Parse ((partnerInfoDic [i] [0].ToString ()));
			
			Point partnerId = new Point (0, 0, objectId);
		
			string[] infoStrs = SqliteReader.getInstance ().getIniVal ("Partner", "PartnerID", partnerId.QuerySrvId ().ToString (), false, new string[]{"ModelName","HeadIcon"});
		
			partnerDic [i].replaceSprite.atlas = headPicAtlas;
			partnerDic [i].replaceSprite.spriteName = infoStrs [1];
			partnerDic [i].replaceSprite.MakePixelPerfect ();
			string atlasPath = infoStrs [0];
			Item tItem = new Item (atlasPath);
			partnerDic [i].myItem = tItem;
			partnerDic [i].icon.atlas = tItem.Atlas;
		}
		
		if (index < 0) {
			bool hasLastOpen = false;
			for (int i = 0; i < campInfoDic.Count; i++) {
				int lastOpenFlag = (int)(campInfoDic [i] [7]);
				if (lastOpenFlag == 1) {
					for (int j = 0; j < 6; j++) {
						ulong objectId = ulong.Parse ((campInfoDic [i] [j].ToString ()));
						Point pos1 = new Point (0, 0, objectId);
						if (pos1.z != tPoint_0) {
							string modelName = "";
							if (pos1.QueryType () == (byte)GameDefine.GameObjectType.GAMEOBJECT_PLAYER) {
								modelName = ModelLocator.getInstance ().scene.Role.GetProperties ("ModelName").ToString ();
							} else {
								modelName = SqliteReader.getInstance ().getIniVal ("Partner", "PartnerID", pos1.ToString (), false, new string[]{"ModelName"}) [0];
								
								ShowInUse (pos1);
								
								inUsePartnerCount ++;
							}
							Item item = new Item (modelName);
							partnerPosDic [j].myItem = item;
							partnerPosDic [j].Refresh ();
						}
					}
					
					//宠物//
					
					
					hasLastOpen = true;
					currentArragement = i;
					break;
					
				} else if (lastOpenFlag == 0) {
					hasLastOpen = false;
				}
			}
			
			if (hasLastOpen == false) {
				ShowArrangement (0);
				return;
			} else {
				ShowArrangement (currentArragement);
			}
			
		} else {
			for (int j = 0; j < 6; j++) {
				ulong objectId = ulong.Parse ((campInfoDic [index] [j].ToString ()));
				Point pos1 = new Point (0, 0, objectId);
				if (pos1.z != tPoint_0) {
					string modelName = "";
					if (pos1.QueryType () == (byte)GameDefine.GameObjectType.GAMEOBJECT_PLAYER) {
						modelName = ModelLocator.getInstance ().scene.Role.GetProperties ("ModelName").ToString ();
					} else {
						modelName = SqliteReader.getInstance ().getIniVal ("Partner", "PartnerID", pos1.ToString (), false, new string[]{"ModelName"}) [0];
						ShowInUse (pos1);
						
						inUsePartnerCount ++;
					}
					
					partnerPosDic [j].myItem = new Item (modelName);
					
					partnerPosDic [j].Refresh ();
					
				} else {
					if (partnerPosDic [j].myItem != null) {
						partnerPosDic [j].myItem.Visible = GameDefine.INVISIABLE;
						partnerPosDic [j].Refresh ();
					}
				}
			}
					
			//宠物//
		}
		
		if (isOrderVisible == true) {
			ShowOrder (isOrderVisible);
		}
		
		partnerCountLabel.text = partnerInfoDic.Count.ToString () + "/" + GameDefine.MAXPARTNERCOUNT.ToString ();
		
		inusePartnerLabel.text = inUsePartnerCount + "/" + GameDefine.MAXPARTNERUSECOUNT;
		
		if (index == -1)
			index = 0;
		
		currentArragement = index;
	}
	
	void ShowPartnerInfo (int index)
	{
		ulong objectId = ulong.Parse ((partnerInfoDic [index] [0].ToString ()));
		
		Point partnerId = new Point (0, 0, objectId);
		
		string[] infoStrs = SqliteReader.getInstance ().getIniVal ("Partner", "PartnerID", partnerId.QuerySrvId ().ToString (), false, new string[]{"ModelName","HeadIcon"});
		
		partnerDic [index].replaceSprite.atlas = headPicAtlas;
		partnerDic [index].replaceSprite.spriteName = infoStrs [1];
		partnerDic [index].replaceSprite.MakePixelPerfect ();
		string atlasPath = infoStrs [0];
		Item tItem = new Item (atlasPath);
		partnerDic [index].myItem = tItem;
		partnerDic [index].icon.atlas = tItem.Atlas;
		
		partnerCountLabel.text = partnerInfoDic.Count.ToString () + "/" + GameDefine.MAXPARTNERCOUNT.ToString ();
	}
	
	//移动请求//
	void MoveOrEquipRequest (BackpackItem item)
	{
		targetItem = item;
		
		ByteArrayEx byteArray = new ByteArrayEx ();
		if (targetItem.storageState == BackpackItem.StorageStateType.Arrangement) {
			if (targetItem.targetItem != null) {
				if (targetItem.targetItem.storageState == BackpackItem.StorageStateType.Arrangement) {
					byteArray.writeInt ((int)SystemMsgFlag.NetMessageCS.NM_CS_CAMP_EXCHANGE_SYN);
					byteArray.writeByte ((byte)currentArragement);
					byteArray.writeByte ((byte)targetItem.index);
					byteArray.writeByte ((byte)targetItem.targetItem.index);
				} else if (targetItem.targetItem.storageState == BackpackItem.StorageStateType.Other) {
					byteArray.writeInt ((int)SystemMsgFlag.NetMessageCS.NM_CS_CAMP_DEL_PARTER_SYN);
					byteArray.writeByte ((byte)currentArragement);
					byteArray.writeByte ((byte)targetItem.index);
				}
			}
		} else {
			if (targetItem.targetItem != null) {
				if (targetItem.targetItem.storageState == BackpackItem.StorageStateType.Arrangement) {
					byteArray.writeInt ((int)SystemMsgFlag.NetMessageCS.NM_CS_CAMP_ADD_PARTER_SYN);
					byteArray.writeByte ((byte)currentArragement);
					byteArray.writeByte ((byte)targetItem.index);
					byteArray.writeByte ((byte)targetItem.targetItem.index);
				} else {
					Cursor.Clear ();
					targetItem.icon.enabled = targetItem.myItem.Visible;
		
					targetItem.canDrop = false;
				}
			}
		}
		
		MySocket.getInstance ().Async_Send (byteArray.byteArray);
	}
	
	//移动返回//
	void ExchangeArrangement (System.Object getter, DispatchEventArgs e)
	{
		ByteArrayEx byteArray = new ByteArrayEx (e.data [0] as byte[]);
		
		byte result = byteArray.readByte ();
		if (result == (byte)CustomToClientFlag.RequestResult.success) {
			if (targetItem.storageState == BackpackItem.StorageStateType.Arrangement) {
				targetItem.myItem.Exchange (targetItem.targetItem.myItem);
				
				targetItem.targetItem.Refresh ();
				targetItem.Refresh ();
				
				if (targetItem.targetItem.storageState == BackpackItem.StorageStateType.Other) {
					int tIndex = targetItem.index;
					ulong objectId = ulong.Parse ((campInfoDic [currentArragement] [tIndex].ToString ()));
					Point pos1 = new Point (0, 0, objectId);
					
					ShowNotInUse (pos1);
					
					targetItem.myItem.Visible = GameDefine.INVISIABLE;
					
					inUsePartnerCount --;
				} else if (targetItem.targetItem.storageState == BackpackItem.StorageStateType.Arrangement) {
					//object t_Id = campInfoDic [currentArragement] [targetItem.index];
					
					//campInfoDic [currentArragement] [targetItem.index]
				}
			} else {
				if (targetItem.targetItem != null && targetItem.targetItem.storageState == BackpackItem.StorageStateType.Arrangement) {
					targetItem.myItem.Exchange (targetItem.targetItem.myItem);
					
					targetItem.targetItem.Refresh ();
					targetItem.Refresh ();
					
					int tIndex = targetItem.index;
					ulong objectId = ulong.Parse ((partnerInfoDic [tIndex] [0].ToString ()));
					Point pos1 = new Point (0, 0, objectId);
					ShowInUse (pos1);
					
					inUsePartnerCount ++;
				}
			}
		} else {
			
		}
		
		if (targetItem.targetItem != null)
			targetItem.targetItem = null;
		
		Cursor.Clear ();
		targetItem.icon.enabled = targetItem.myItem.Visible;
		
		if (isOrderVisible == true) {
			ShowOrder (isOrderVisible);
		}
		
		targetItem.canDrop = false;
		
		inusePartnerLabel.text = inUsePartnerCount + "/" + GameDefine.MAXPARTNERUSECOUNT;
	}
	
	void GetPartnerInfo ()
	{
		Record campRecord = ModelLocator.getInstance ().scene.Role.GetRecordEx ("Camp") as Record;
		
		//ModelLocator.getInstance ().scene.Role.PrintKeyAndValue();
		
		campRecord.recArr.TrimToSize ();
		for (int i = 0; i < campRecord.recArr.Count; i++) {
			ArrayList rowArr = (ArrayList)campRecord.recArr [i];
			ArrayList rowItems = (ArrayList)rowArr [0];
			if (campInfoDic.ContainsKey (i)) {
				campInfoDic [i] = rowItems;
			} else {
				campInfoDic.Add (i, rowItems);
			}
		}
		
		Record partnerRecord = ModelLocator.getInstance ().scene.Role.GetRecordEx ("Partner") as Record;
		
		partnerRecord.recArr.TrimToSize ();
		for (int i = 0; i < partnerRecord.recArr.Count; i++) {
			ArrayList partnerArr = (ArrayList)partnerRecord.recArr [i];
			ArrayList rowItems = (ArrayList)partnerArr [0];
			if (partnerInfoDic.ContainsKey (i)) {
				partnerInfoDic [i] = rowItems;
			} else {
				partnerInfoDic.Add (i, rowItems);
			}
		}
	}
	
	/*
	//第一个参数是int,第二个参数是ArrayList//
	public void BingPartner (object columnIndex, object strList)
	{
		int recordRow = (int)columnIndex;
		
		Debug.Log ("BingPartner<----------->" + recordRow);
		
		ArrayList lists = (ArrayList)strList;
		
		if (partnerInfoDic.ContainsKey (recordRow)) {
			partnerInfoDic [recordRow] = (ArrayList)lists ;
		} else {
			partnerInfoDic.Add (recordRow, (ArrayList)lists );
		}
		
		//ShowPartnerInfo (recordRow);
	}
	
	//第一个参数是int,第二个参数是ArrayList//
	public void RemovePartner (object columnindex, object strList)
	{
		
	}
	*/
	
	//第一个参数是int,第二个参数是ArrayList//
	public void BingCamp (object columnIndex, object strList)
	{
		try {
			int recordRow = int.Parse (columnIndex.ToString ());
		
			Debug.Log ("BingCamp<----------->" + recordRow);
			
			ArrayList lists = (ArrayList)strList;
			
			if (campInfoDic.ContainsKey (recordRow)) {
				campInfoDic [recordRow] = (ArrayList)lists;
			} else {
				campInfoDic.Add (recordRow, (ArrayList)lists);
			}
		} catch (Exception ex) {
			Debug.Log (ex.ToString ());
		}
		
		
		//ShowArrangement (currentArragement);
	}
	
	
	
	//第一个参数是int,第二个参数是ArrayList//
	public void RemoveCamp (object columnindex, object strList)
	{
		
	}
	
	void ShowInUse (Point inUseObjectId)
	{
		for (int i = 0; i < partnerInfoDic.Count; i++) {
			if (ulong.Parse (partnerInfoDic [i] [0].ToString ()) == inUseObjectId.z) {
				string spriteName = partnerDic [i].replaceSprite.spriteName;
				partnerDic [i].replaceSprite.atlas = greyHeadPicAtals;
				
				partnerDic [i].replaceSprite.spriteName = spriteName;
				
				Debug.Log ("ChangeGrey");
			}
		}
	}
	
	void ShowNotInUse (Point inUseObjectId)
	{
		for (int i = 0; i < partnerInfoDic.Count; i++) {
			if (ulong.Parse (partnerInfoDic [i] [0].ToString ()) == inUseObjectId.z) {
				string spriteName = partnerDic [i].replaceSprite.spriteName;
				partnerDic [i].replaceSprite.atlas = headPicAtlas;
				partnerDic [i].replaceSprite.spriteName = spriteName;
				
				Debug.Log ("ChangeShine");
			}
		}
	}
	
	void ShowOrder (bool isActive)
	{
		isOrderVisible = isActive;
		
		orderParent.gameObject.SetActive (isActive);
		
		int orderIndex = 0;
		if (isActive == true) {
			for (int i = 0; i < partnerPosDic.Count; i++) {
				if (partnerPosDic [i].myItem.Visible == GameDefine.VISIABLE) {
					orderIndex ++;
					orderTransformDic [i].gameObject.SetActive (true);
					Transform num = orderTransformDic [i].Find ("Num");
					UISprite numSprite = num.GetComponent<UISprite> ();
					numSprite.spriteName = spriteNamePre + orderIndex;
				} else {
					orderTransformDic [i].gameObject.SetActive (false);
				}
			}
		}
	}
	
	void OnDestroy ()
	{
		MySocket.getInstance ().removeEventListener ((int)SystemMsgFlag.NetMessageSC.NM_SC_CAMP_OPEN_ACK);
		MySocket.getInstance ().removeEventListener ((int)SystemMsgFlag.NetMessageSC.NM_SC_CAMP_EXCHANGE_ACK);
		MySocket.getInstance ().removeEventListener ((int)SystemMsgFlag.NetMessageSC.NM_SC_CAMP_SWITCH_ACK);
		MySocket.getInstance ().removeEventListener ((int)SystemMsgFlag.NetMessageSC.NM_SC_CAMP_ADD_PARTER_ACK);
		MySocket.getInstance ().removeEventListener ((int)SystemMsgFlag.NetMessageSC.NM_SC_CAMP_DEL_PARTER_ACK);
		
		//BindManage.getInstance ().UnbindRecord ("Partner", bingPartnerIndex);
		
		BindManage.getInstance ().UnbindRecord ("Camp", bingCampIndex);
	}
}
